package com.google.code.p.narcissus.ui.preferences;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;

import com.thoughtworks.xstream.XStream;

/**
 * @author jadoj
 */
public class NarcissusUIPreferences {

	private static final Logger LOGGER = Logger.getLogger(NarcissusUIPreferences.class.getName());

	private static final File userPreferencesFile = new File(System.getProperty("user.home") + "/narcissus/UIPreferences.xml");

	private String rootFolder;

	private String referenceCommentsFile;

	private static NarcissusUIPreferences preferences;

	public static NarcissusUIPreferences getInstance() {
		if (preferences == null) {
			preferences = load();
		}

		return preferences;
	}

	private NarcissusUIPreferences() {
	}

	public String getRootFolder() {
		return rootFolder;
	}

	public void setRootFolder(String rootFolder) {
		this.rootFolder = rootFolder;
	}

	public String getReferenceCommentsFile() {
		return referenceCommentsFile;
	}

	public void setReferenceCommentsFile(String referenceCommentsFile) {
		this.referenceCommentsFile = referenceCommentsFile;
	}

	private static NarcissusUIPreferences load() {
		try {
			final XStream streamReader = new XStream();
			streamReader.alias("UIPreferences", NarcissusUIPreferences.class);
			preferences = (!userPreferencesFile.exists()) ? new NarcissusUIPreferences() : (NarcissusUIPreferences) streamReader
					.fromXML(new BufferedInputStream(new FileInputStream(userPreferencesFile)));
		} catch (FileNotFoundException ex) {
			LOGGER.error("Impossible to load preferences file!", ex);
			preferences = new NarcissusUIPreferences();
		}

		return preferences;
	}

	public void save() {
		XStream streamer = new XStream();
		streamer.alias("UIPreferences", NarcissusUIPreferences.class);
		try {
			if (userPreferencesFile.getParentFile() != null) {
				userPreferencesFile.getParentFile().mkdirs();
			}

			streamer.toXML(preferences, new BufferedOutputStream(new FileOutputStream(userPreferencesFile)));
		} catch (FileNotFoundException impossibleToSavePreferencesEx) {
			LOGGER.error("Impossible to save preferences file!", impossibleToSavePreferencesEx);
		}
	}
}